<style scoped lang="scss">
@import url('index.scss');
</style>

<template>
  <div class="app-container">
    <!--新模版样式-->
    <div class="topsearch">
      <el-row>
        <el-col :span="22" class="searchcol">
          <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
            <!-- <el-form-item label="排班年度" prop="workYear">
              <el-input v-model="queryParams.workYear" placeholder="请输入排班年度" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item label="排班日期" prop="workDate">
              <el-input v-model="queryParams.workDate" placeholder="请输入排班日期" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="排班医生" prop="doctorCode">
              <el-input v-model="queryParams.doctorCode" placeholder="请输入排班医生" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="院区" prop="hospitalCode">
              <el-input v-model="queryParams.hospitalCode" placeholder="请输入院区" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="排班科室" prop="kid">
              <el-input v-model="queryParams.kid" placeholder="请输入排班科室" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="排班诊室" prop="roomNo">
              <el-input v-model="queryParams.roomNo" placeholder="请输入排班诊室" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="最多号源" prop="maxPatient">
              <el-input v-model="queryParams.maxPatient" placeholder="请输入最多号源" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="已约人数" prop="bookedNum">
              <el-input v-model="queryParams.bookedNum" placeholder="请输入已约人数" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="辐射安全活度" prop="maxActivityMbq">
              <el-input v-model="queryParams.maxActivityMbq" placeholder="请输入辐射安全活度" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="排班人" prop="suser">
              <el-input v-model="queryParams.suser" placeholder="请输入排班人" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22" class="rightcol">
          <div class="newbtn" @click="handleAdd" v-hasPermi="['system:schedules:add']">
            <img src="@/assets/images/add.svg" alt="">
            <span>新建</span>
          </div>
          <div class="newbtn" v-if="single == false" @click="handleUpdate" v-hasPermi="['system:schedules:edit']">
            <img src="@/assets/images/edit.svg" alt=""></img>
            <span>编辑</span>
          </div>
          <div class="newbtn" v-if="multiple == false" @click="handleDelete" v-hasPermi="['system:schedules:remove']">
            <img src="@/assets/images/del.svg" alt=""></img>
            <span>删除</span>
          </div>
          <div class="newbtn" @click="handleExport" v-hasPermi="['system:schedules:export']">
            <img src="@/assets/images/export.svg" alt=""></img>
            <span>导出</span>
          </div>
          <div class="newbtn" @click="getList">
            <img src="@/assets/images/refresh.svg" alt=""></img>
            <span>刷新</span>
          </div>
        </el-col>
      </el-row>
    </div>




    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:schedules:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:schedules:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:schedules:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:schedules:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->


    <el-table v-loading="loading" :data="schedulesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="55" />
      <el-table-column label="排班医生" align="center" prop="doctorCode">
        <template #default="scope">
          <!-- {{ scope.row.doctorCode }}
          {{  scope.row.docList }} -->
          {{scope.row.doctorCode ? JSON.parse(scope.row.doctorCode).map(item =>
            scope.row.docList.find(listItem => listItem.did == item)?.dname).join(',') : '-'}}
        </template>
      </el-table-column>
      <!-- <el-table-column label="排班年度" align="center" prop="workYear" /> -->
      <el-table-column label="排班日期" align="center" prop="workDate" />
      <el-table-column label="排班班次" min-width="120" align="center" prop="workType">
        <template #default="scope">
          <!-- {{ scope.row.workType }}
          {{ workTypeList }} -->
          {{workTypeList.find(item => item.sid === scope.row.workType)?.shitName || '-'}}
          <span>(
            {{workTypeList.find(item => item.sid === scope.row.workType)?.startTime || '-'}} -
            {{workTypeList.find(item => item.sid === scope.row.workType)?.endTime || '-'}}
            )</span>
        </template>
      </el-table-column>
      <el-table-column label="院区" align="center" prop="hospitalCode" />
      <el-table-column label="排班科室" align="center" prop="kid">
        <template #default="scope">
          {{departmentList.find(item => item.kid === scope.row.kid)?.kname || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="排班诊室" align="center" prop="roomNo">
        <template #default="scope">
          <!-- {{ scope.row.roomNo }} -->
            <!-- {{ scope.row.roomList }} -->
            {{ scope.row.roomList.find(item => item.cid === scope.row.roomNo)?.roomname || '-' }}
           ({{ scope.row.roomList.find(item => item.cid === scope.row.roomNo)?.roomnumber || '-' }}) 
        </template>
      </el-table-column>
      <el-table-column label="最多号源" align="center" prop="maxPatient" />
      <el-table-column label="已约人数" align="center" prop="bookedNum" />
      <el-table-column label="排班状态" align="center" prop="workStatus">
        <template #default="scope">
          <el-tag :type="scope.row.workStatus === '1' ? 'success' : 'danger'">
            {{ ha_schedules_status.find(item => item.value === scope.row.workStatus)?.label || '-' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="辐射安全活度" align="center" prop="maxActivityMbq" />
      <el-table-column label="排班人" align="center" prop="suser" />
      <el-table-column label="排班备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:schedules:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:schedules:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改排班列表对话框 -->
    <el-dialog :title="title" v-model="open" width="50%" class="newDialog">
      <el-form ref="schedulesRef" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="排班年度" prop="workYear">
          <el-input v-model="form.workYear" placeholder="请输入排班年度" />
        </el-form-item> -->
        <el-form-item label="院区" prop="hospitalCode">
          <el-input v-model="form.hospitalCode" placeholder="请输入院区" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班科室" prop="kid">
              <!-- <el-input v-model="form.kid" placeholder="请输入排班科室" /> -->
              <el-select v-model="form.kid" placeholder="请选择排班科室" clearable @change="getRoomList">
                <el-option v-for="item in departmentList" :key="item.kid" :label="item.kname" :value="item.kid" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排班诊室" prop="roomNo">
              <!-- <el-input v-model="form.roomNo" placeholder="请输入排班诊室" :disabled="disabledRoomNo" /> -->
              <el-select v-model="form.roomNo" placeholder="请选择排班诊室" clearable :disabled="disabledRoomNo">
                <el-option v-for="item in roomList" :key="item.cid" :label="item.roomname" :value="item.cid" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班日期" prop="workDate">
              <!-- <el-input v-model="form.workDate" placeholder="请输入排班日期" /> -->
              <el-date-picker clearable v-model="form.workDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请输入排班日期" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排班班次" prop="workType">
              <!-- <el-input v-model="form.workType" placeholder="请输入排班班次" /> -->
              <el-select v-model="form.workType" placeholder="请选择排班班次" clearable>
                <el-option v-for="item in workTypeList" :key="item.sid"
                  :label="item.shitName+'('+item.startTime+'-'+item.endTime+')'" :value="item.sid" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="排班医生" prop="doctorCode">
              <el-transfer v-model="form.doctorCode" :props="{
                key: 'did',
                label: 'dname',
                value: 'did',
              }" filter-placeholder="请选择排班医生" :data="doctorList" :titles="['医生列表', '已选择医生']" />
            </el-form-item>

          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最多号源" prop="maxPatient">
              <el-input v-model="form.maxPatient" placeholder="请输入最多号源" type="number" min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已约人数" prop="bookedNum">
              <el-input v-model="form.bookedNum" placeholder="请输入已约人数" type="number" min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="辐射安全活度" prop="maxActivityMbq">
              <el-input v-model="form.maxActivityMbq" placeholder="请输入辐射安全活度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排班人" prop="suser">
              <el-input v-model="form.suser" placeholder="请输入排班人" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排班状态" prop="workStatus">
              <el-select v-model="form.workStatus" placeholder="请选择排班状态" clearable>
                <el-option v-for="item in ha_schedules_status" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排班备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入排班备注" type="textarea" :rows="6" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Schedules">
import { listSchedules, getSchedules, delSchedules, addSchedules, updateSchedules } from "@/api/system/schedules"
import { listDepartment } from "@/api/system/department"
import { listConsultingroom } from "@/api/system/consultingroom"
import { listSchtype } from "@/api/system/schtype"
import { listDoctors } from "@/api/system/doctors"
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
// console.log(userStore.name)

const { proxy } = getCurrentInstance()

const { ha_schedules_status } = proxy.useDict('ha_schedules_status') //排班状态


const schedulesList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
// 排班科室选择后，是否禁用排班诊室
const disabledRoomNo = ref(true)
// 排班科室选择后，根据科室查询诊室列表
const roomList = ref([])
// 排班科室选择后，根据科室查询班次列表
const workTypeList = ref([])


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    workYear: null,
    workDate: null,
    workType: null,
    doctorCode: null,
    hospitalCode: null,
    kid: null,
    roomNo: null,
    maxPatient: null,
    bookedNum: null,
    workStatus: null,
    maxActivityMbq: null,
    suser: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

const newqueryParams = {
  pageNum: 1,
  pageSize: 1000,
}
// 获取科室列表
const departmentList = ref([])

const doctorList = ref([])  //获取的医生列表

onMounted(async () => {
  //列出所有的科室
  getDepartmentList()
  //获取所有的班次
  getWorkTypeList()
 //end
})

//监听科室的选择，如果有选择科室了，就查询医生
watch(() => form.value.kid, (newVal, oldVal) => {
  if(newVal){
    getDoctorList()
  }
})


//获取一下排班的医生,要按照科室来选择@鲍小伟1117
function getDoctorList() {
  const newqueryParamsDoctor = {
    pageNum: 1,
    pageSize: 1000,
    deptcode: form.value.kid,
  }
  listDoctors(newqueryParamsDoctor).then(response => {
    console.log(response)
    if(response.code == 200){
      doctorList.value = response.rows
    } else {
      doctorList.value = []
    }
  })
}

// function getDoctorListNew(kid) {
//   const newqueryParamsDoctor = {
//     pageNum: 1,
//     pageSize: 1000,
//     deptcode: kid,
//   }
//   listDoctors(newqueryParamsDoctor).then(response => {
//     console.log(response.rows)
//     return response.rows
//   })
// }
// 排班科室选择后，根据科室查询诊室列表
function getWorkTypeList() {
  listSchtype(newqueryParams).then(response => {
    console.log(response)
    if(response.code == 200){
      workTypeList.value = response.rows
    } else {
      workTypeList.value = []
    }
  })
}

// 获取诊室列表@鲍小伟20251117
function getRoomList() {
  listConsultingroom({ kid: form.value.kid }).then(response => {
    console.log(response)
    disabledRoomNo.value = false
    if(response.total >0 && response.code == 200){
      roomList.value = response.rows
    } else {
      roomList.value = []
      form.value.roomNo = null //没有就清空
    }
  })
}

// 获取科室列表@鲍小伟20251111
function getDepartmentList() {
  listDepartment(newqueryParams).then(response => {
    console.log(response)
    if(response.code == 200){
      departmentList.value = response.rows
    } else {
      departmentList.value = []
    }
  })
}

/** 查询排班列表列表 */
function getList() {
  loading.value = true
  listSchedules(queryParams.value).then(response => {
    schedulesList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    workYear: null,
    workDate: null,
    workType: null,
    doctorCode: [], //穿梭框这里要赋值为空数据
    hospitalCode: null,
    kid: null,
    roomNo: null,
    maxPatient: null,
    bookedNum: null,
    workStatus: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    maxActivityMbq: null,
    suser: userStore.name,
    remark: null
  }
  proxy.resetForm("schedulesRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加排班列表"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getSchedules(_id).then(response => {
    //处理一下格式问题
    form.value = response.data
    form.value.doctorCode = response.data.doctorCode?JSON.parse(response.data.doctorCode):[]
    form.value.suser = userStore.name //当前登录用户
    //需要获取一份诊室列表
    getRoomList()
    open.value = true
    title.value = "修改排班列表"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["schedulesRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        //处理一下格式问题
        form.value.doctorCode = JSON.stringify(form.value.doctorCode)
        //年份为日期选择前四位
        form.value.workYear = form.value.workDate.substring(0, 4)
        updateSchedules(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        //处理一下格式问题
        form.value.doctorCode = JSON.stringify(form.value.doctorCode)
        //年份为日期选择前四位
        form.value.workYear = form.value.workDate.substring(0, 4)
        addSchedules(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除排班列表编号为"' + _ids + '"的数据项？').then(function() {
    return delSchedules(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/schedules/export', {
    ...queryParams.value
  }, `schedules_${new Date().getTime()}.xlsx`)
}

getList()
</script>
